package com.ruoyi.system.service.impl;

import java.util.List;

import com.ruoyi.system.domain.TaskInfo;
import com.ruoyi.system.service.IUserTaskLikeService;
import com.ruoyi.system.service.IUserTaskStarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.mapper.TaskCommentMapper;
import com.ruoyi.system.mapper.TaskInfoMapper;
import com.ruoyi.system.service.ITaskInfoService;
import com.ruoyi.system.mapper.UserTaskStarMapper;
import com.ruoyi.system.domain.UserTaskStar;
import com.ruoyi.system.service.IUserTaskApplyService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.IUserFollowService;

/**
 * 任务信息 服务层实现
 */
@Service
public class TaskInfoServiceImpl implements ITaskInfoService
{
    @Autowired
    private TaskInfoMapper taskInfoMapper;

    @Autowired
    private IUserTaskLikeService userTaskLikeService;

    @Autowired
    private IUserTaskStarService userTaskStarService;

    @Autowired
    private IUserFollowService userFollowService;

    @Autowired
    private TaskCommentMapper taskCommentMapper;

    @Autowired
    private UserTaskStarMapper userTaskStarMapper;

    @Autowired
    private IUserTaskApplyService userTaskApplyService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDictDataService dictDataService;

    /**
     * 查询任务信息列表
     *
     * @param taskInfo 任务信息
     * @return 任务信息集合
     */
    @Override
    public List<TaskInfo> selectTaskInfoList(TaskInfo taskInfo, Long currentUserId)
    {
        List<TaskInfo> taskInfos = taskInfoMapper.selectTaskInfoList(taskInfo);

        for (TaskInfo info : taskInfos) {
            // 设置发布者信息
            if (info.getCreateBy() != null && !info.getCreateBy().isEmpty()) {
                try {
                    SysUser user = userService.selectUserById(Long.parseLong(info.getCreateBy()));
                    if (user != null) {
                        info.setUserName(user.getNickName());
                        info.setUserAvatar(user.getAvatar());
                    }
                } catch (NumberFormatException e) {
                    // Log error or handle exception
                }
            }
            
            // 设置职位类别名称
            if (info.getCategoryId() != null) {
                info.setCategory(dictDataService.selectDictLabel("task_category_type", info.getCategoryId().toString()));
            }

            // 设置当前用户的点赞和收藏状态
            if (currentUserId != null) {
                info.setLiked(userTaskLikeService.checkUserLikedTask(currentUserId, info.getTaskId()));
                info.setStarred(userTaskStarService.checkUserStarredTask(currentUserId, info.getTaskId()));
            }
        }

        return taskInfos;
    }

    /**
     * 查询任务信息
     *
     * @param taskId 任务ID
     * @return 任务信息
     */
    @Override
    public TaskInfo selectTaskInfoById(Long taskId, Long currentUserId)
    {
        TaskInfo taskInfo = taskInfoMapper.selectTaskInfoById(taskId);
        if (taskInfo != null) {
            // 设置发布者信息
            if (taskInfo.getCreateBy() != null && !taskInfo.getCreateBy().isEmpty()) {
                try {
                    SysUser user = userService.selectUserById(Long.parseLong(taskInfo.getCreateBy()));
                    if (user != null) {
                        taskInfo.setUserName(user.getNickName());
                        taskInfo.setUserAvatar(user.getAvatar());
                    }
                } catch (NumberFormatException e) {
                    // Log error or handle exception if createBy is not a valid Long
                }
            }

            // 设置职位类别名称
            if (taskInfo.getCategoryId() != null) {
                taskInfo.setCategory(dictDataService.selectDictLabel("task_category_type", taskInfo.getCategoryId().toString()));
            }

            // 设置当前用户的点赞和收藏状态
            if (currentUserId != null) {
                taskInfo.setLiked(userTaskLikeService.checkUserLikedTask(currentUserId, taskId));
                taskInfo.setStarred(userTaskStarService.checkUserStarredTask(currentUserId, taskId));
                if (taskInfo.getUserId() != null) {
                    taskInfo.setFollowing(userFollowService.checkUserFollowed(currentUserId, taskInfo.getUserId()));
                }
            }
        }
        // 获取评论数量
        int commentCount = taskCommentMapper.countTaskCommentsByTaskId(taskId);
        if (taskInfo != null) {
            taskInfo.setCommentCount((long) commentCount);
        }
        return taskInfo;
    }

    /**
     * 根据状态查询任务
     *
     * @param status 任务状态
     * @return 任务信息集合
     */
    @Override
    public List<TaskInfo> selectTaskInfoByStatus(Integer status)
    {
        return taskInfoMapper.selectTaskInfoByStatus(status);
    }

    /**
     * 新增任务信息
     *
     * @param taskInfo 任务信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTaskInfo(TaskInfo taskInfo)
    {
        taskInfo.setCreateTime(DateUtils.getNowDate());
        return taskInfoMapper.insertTaskInfo(taskInfo);
    }

    /**
     * 修改任务信息
     *
     * @param taskInfo 任务信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateTaskInfo(TaskInfo taskInfo)
    {
        taskInfo.setUpdateTime(DateUtils.getNowDate());
        return taskInfoMapper.updateTaskInfo(taskInfo);
    }

    /**
     * 批量删除任务信息
     *
     * @param taskIds 需要删除的任务ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteTaskInfoByIds(Long[] taskIds)
    {
        for (Long taskId : taskIds)
        {
            TaskInfo taskInfo = selectTaskInfoById(taskId, null);
            if (taskInfo.getStatus() == 1)
            {
                throw new ServiceException(String.format("%1$s正在进行中，不能删除", taskInfo.getTitle()));
            }
        }
        return taskInfoMapper.deleteTaskInfoByIds(taskIds);
    }

    /**
     * 查询用户收藏的任务列表
     * @param userId 用户ID
     * @return 任务信息集合
     */
    @Override
    public List<TaskInfo> selectStarTaskListByUserId(Long userId) {
        UserTaskStar query = new UserTaskStar();
        query.setUserId(userId);
        List<UserTaskStar> starList = userTaskStarMapper.selectUserTaskStarList(query);

        if (starList == null || starList.isEmpty()) {
            return java.util.Collections.emptyList();
        }

        List<Long> taskIds = new java.util.ArrayList<>();
        for (UserTaskStar star : starList) {
            taskIds.add(star.getTaskId());
        }

        // 使用批量查询替代N+1查询
        return selectTaskInfoListByIds(taskIds);
    }

    @Override
    public java.util.List<TaskInfo> selectTaskInfoListByIds(java.util.List<Long> taskIds) {
        if (taskIds == null || taskIds.isEmpty()) {
            return new java.util.ArrayList<>();
        }
        return taskInfoMapper.selectTaskInfoListByIds(taskIds);
    }

    @Override
    public int selectTaskInfoCountByUserId(Long userId)
    {
        return taskInfoMapper.selectTaskInfoCountByUserId(userId);
    }

    @Override
    public java.util.Map<String, Object> getUserStats(Long userId)
    {
        java.util.Map<String, Object> stats = new java.util.HashMap<>();
        stats.put("notesCount", selectTaskInfoCountByUserId(userId));
        stats.put("collectsCount", userTaskStarService.countByUserId(userId));
        stats.put("appliedCount", userTaskApplyService.countByUserId(userId));
        return stats;
    }

    @Override
    public List<TaskInfo> selectTasksFromFollowedUsers(Long userId) {
        return taskInfoMapper.selectTasksFromFollowedUsers(userId);
    }
}